package main;

import main.UI.GUI;
import main.UI.misc.ErrorHandling;
import main.database.DatabaseException;

import javax.swing.*;
import java.awt.*;
import java.io.*;

/**
 * Created by Sknictik on 28.12.13
 * The class that starts it all
 */
public class Main {

    public static void main(String[] args) {
        //L&F myst be set before initialising interface
        try {
            for (UIManager.LookAndFeelInfo info : UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
            UIManager.put("Button.contentMargins", new Insets(6, 8, 6, 8));
            UIManager.put("Tree.expandedIcon", new ImageIcon("src/main/res/oie_transparent.png"));
        } catch (Exception e) {
          //In this case let it be default L&F
        }

        try {
            configCheck();
        }
        catch (Exception ex) {
            ex.printStackTrace();
            ErrorHandling.showError(ex, "Ошибка при копировании файла настроек", false);
        }

        GUI mainGUI = new GUI();
        mainGUI.pack();
        GUI.centerDialog(mainGUI);
           /* if (!SQLManager.createSQLDatabase("testBase"))
            {
                JOptionPane.showMessageDialog(mainGUI, "Ошибка при создании базы данных.");
                System.exit(1);
            }*/
        try {
            GUI.updateExpenseTable();
            GUI.updateProductTable();
            GUI.updateCategoryTable();
        }
        catch (DatabaseException ex) {
            ErrorHandling.showError(ex, "Ошибка при получении записей из базы данных", false);
        }
        mainGUI.setVisible(true);
    }

    private static void configCheck() throws Exception{
        File config = new File("./hibernate.cfg.xml");
        if (config.exists())
            //noinspection UnnecessaryReturnStatement
            return;
        else {
            //String path = Main.class.getProtectionDomain().getCodeSource().getLocation().getPath();
            //String decodedPath = URLDecoder.decode(path, "UTF-8");
            //File defaultConfig = new File(decodedPath + "/hibernate.cfg.xml");
            copyDefaultConfig(config);
        }

    }

    public static void copyDefaultConfig(File destFile) throws IOException {
        if (destFile.createNewFile())
            System.out.println("Default configuration file created");

        InputStream defaultConfigStream = null;

        FileWriter configStream = new FileWriter(destFile);
        try {
            defaultConfigStream = ClassLoader.getSystemResourceAsStream("hibernate.cfg.xml");

            BufferedReader reader = new BufferedReader(new InputStreamReader(defaultConfigStream));
            String str;
            StringBuilder buf = new StringBuilder();

            if (defaultConfigStream!=null) {
                while ((str = reader.readLine()) != null) {
                    buf.append(str).append("\n");
                }
            }
            configStream.write(buf.toString());
        } finally {
            if (defaultConfigStream != null) {
                defaultConfigStream.close();
            }
            configStream.close();
        }
    }

}
